const App = getApp()
import {IP} from '../constData'
export function request(params) {
  return new Promise((resolve, reject) => {
    tryFn(wxRequest, params, 3).then(res => {
      if(res.code===200){
        resolve(res.data)
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
        reject(res.msg)
      }
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: 'error',
        duration: 1500
      })
      reject(err)
    })
  })
}

function tryFn(fn, params, count) {
  return new Promise((resolve, reject) => {
    // 匿名函数，出现错误时就重复执行
    const run = () => {
      fn(params).then(resolve).catch(err => {
        if (count--) {
          console.log(`第${count}次发起请求`)
          setTimeout(() => {
            run()
          }, 1000)
        } else {
          reject(err)
        }
      })
    }
    run()
  })
}

function wxRequest(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      header: {
        'token': wx.getStorageSync('token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      ...params,

      url: IP + params.url,
      success(res) {
        // 接口没有返回200默认失败
        if (res.data.code == 200 || res.data.code == 500) {
          resolve(res.data)
          return
        }
        let msg = res.data.msg ? res.data.msg : '请求错误'
        reject(msg)
      },
      fail(res) {
        reject(res)
      }
    })
  })
}